Building a Simple Peer-to-Peer WebSocket App

Course- Javascript >

Now, let’s get started with building our application.

Point your browser to the starting state: http://jsfiddle.net/R5qc3/.

Task 1: Adding the slider to the HTML page

Add a slider to the HTML page. First, add a div, and then an input tag, of type range. As the slider changes, we invoke the sliderChange() JavaScript function and pass in the value of the slider as a parameter.

<div id="sliderDiv">
 <input id="slider" type="range" min="0" max="1200" value="600" onchange="sliderChange(this.value)"/>
</div>

The completed HTML file looks as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Kaazing WebSocket Tutorial - JMS</title>
  <script src="http://demo.kaazing.com/lib/client/javascript/StompJms.js" type="text/javascript" language="javascript"></script>
 </head>
 <body onload="doConnect()">
  <!-- Task 1 -->
  <div id="sliderDiv">
   <input id="slider" type="range" min="0" max="1200" value="600" onchange="sliderChange(this.value)"/>
  </div>
  <!-- Task 1 -->
  <div id="logMsgs"></div>
 </body>
</html>

To see the updated code in JSFiddle, point your browser to the Task 1 state: http://jsfiddle.net/R5qc3/1. Run the app, and notice that the slider displays in the Results pane (located in the bottom right corner of JSFiddle).

Note: Notice the pattern: for “Task <n>” the JSFiddle URL with the saved changes is http://jsfiddle.net/R5qc3/<n>.

Task 2: Creating the sliderChange() JavaScript function

Let’s create the JavaScript function, called sliderChange(), that fires every time the slider changes. In this step, we’ll print log information that the slider’s value has changed.

var sliderChange = function(sliderValue) {
  consoleLog("Slider changed: " + sliderValue);
};

Here’s the entire JavaScript file. Look for Task 2 in the comments to find the newly added sliderChange() function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Variables you can change
//
var MY_WEBSOCKET_URL = "ws://tutorial.kaazing.com/jms";
var TOPIC_NAME = "/topic/myTopic";
var IN_DEBUG_MODE = true;
var DEBUG_TO_SCREEN = true;
// WebSocket and JMS variables
//
var connection;
var session;
var wsUrl;
// JSFiddle-specific variables
//
var runningOnJSFiddle = (window.location.hostname === "fiddle.jshell.net");
var WEBSOCKET_URL = (runningOnJSFiddle ? MY_WEBSOCKET_URL : "ws://" + window.location.hostname + ":" + window.location.port + "/jms");
// Variable for log messages
//
var screenMsg = "";
// Used for development and debugging. All logging can be turned
// off by modifying this function.
//
var consoleLog = function(text) {
    if (IN_DEBUG_MODE) {
        if (runningOnJSFiddle || DEBUG_TO_SCREEN) {
            // Logging to the screen
            screenMsg = screenMsg + text + "<br>";
            $("#logMsgs").html(screenMsg);
        } else {
            // Logging to the browser console
            console.log(text);
        }
    }
};
var handleException = function (e) {
    consoleLog("EXCEPTION: " + e);
};
// *** Task 2 ***
var sliderChange = function(sliderValue) {
    consoleLog("Slider changed: " + sliderValue);
};
// *** Task 2 ***
// Connecting...
//
var doConnect = function() {
    // Connect to JMS, create a session and start it.
    //
    var stompConnectionFactory = new StompConnectionFactory(WEBSOCKET_URL);
    try {
        var connectionFuture = stompConnectionFactory.createConnection(function() {
            if (!connectionFuture.exception) {
                try {
                    connection = connectionFuture.getValue();
                    connection.setExceptionListener(handleException);
 
                    consoleLog("Connected to " + WEBSOCKET_URL);
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    connection.start(function() {
                        // Put any callback logic here.
                        //
                        consoleLog("JMS session created");
                    });
                } catch (e) {
                    handleException(e);
                }
            } else {
                handleException(connectionFuture.exception);
            }
        });
    } catch (e) {
        handleException(e);
    }
};

Run the modified app, and notice that as you move the slider, the log messages are printed right underneath it.

JMS session created
Slider changed: 616
Slider changed: 626
Slider changed: 637
Slider changed: 647
Slider changed: 658
Slider changed: 668

To see and run the updated code in JSFiddle, point your browser to the Task 2 state: http://jsfiddle.net/R5qc3/2.

Task 3: Creating a topic
Now, let’s create a topic (or if the topic already exists, get a handle of the topic). Topics in the world of Java Message Service (JMS) serve as a distribution mechanism for publishing messages that are delivered to multiple subscribers. In our case, the publisher will be our app, and the subscriber will be any number of browser windows, running the same HTML5 application.

We will first invoke the createTopic() function on the session object and create a log entry about the successful creation of the topic.

var myTopic = session.createTopic(TOPIC_NAME);
consoleLog("Topic created...");

Here’s the entire JavaScript file. Look for Task 3 in the comments to find the newly added createTopic() function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Variables you can change
//
var MY_WEBSOCKET_URL = "ws://tutorial.kaazing.com/jms";
var TOPIC_NAME = "/topic/myTopic";
var IN_DEBUG_MODE = true;
var DEBUG_TO_SCREEN = true;
 
// WebSocket and JMS variables
//
var connection;
var session;
var wsUrl;
 
// JSFiddle-specific variables
//
var runningOnJSFiddle = (window.location.hostname === "fiddle.jshell.net");
var WEBSOCKET_URL = (runningOnJSFiddle ? MY_WEBSOCKET_URL : "ws://" + window.location.hostname + ":" + window.location.port + "/jms");
 
// Variable for log messages
//
var screenMsg = "";
 
// Used for development and debugging. All logging can be turned
// off by modifying this function.
//
var consoleLog = function(text) {
    if (IN_DEBUG_MODE) {
        if (runningOnJSFiddle || DEBUG_TO_SCREEN) {
            // Logging to the screen
            screenMsg = screenMsg + text + "<br>";
            $("#logMsgs").html(screenMsg);
        } else {
            // Logging to the browser console
            console.log(text);
        }
    }
};
 
var handleException = function (e) {
    consoleLog("EXCEPTION: " + e);
};
 
// *** Task 2 ***
var sliderChange = function(sliderValue) {
    consoleLog("Slider changed: " + sliderValue);
};
// *** Task 2 ***
 
// Connecting...
//
var doConnect = function() {
    // Connect to JMS, create a session and start it.
    //
    var stompConnectionFactory = new StompConnectionFactory(WEBSOCKET_URL);
    try {
        var connectionFuture = stompConnectionFactory.createConnection(function() {
            if (!connectionFuture.exception) {
                try {
                    connection = connectionFuture.getValue();
                    connection.setExceptionListener(handleException);
 
                    consoleLog("Connected to " + WEBSOCKET_URL);
                    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
                    // *** Task 3 ***
                    // Creating topic
                    var myTopic = session.createTopic(TOPIC_NAME);
                    consoleLog("Topic created...");
                    // *** Task 3 ***
 
                    connection.start(function() {
                        // Put any callback logic here.
                        //
                        consoleLog("JMS session created");
                    });
                } catch (e) {
                    handleException(e);
                }
            } else {
                handleException(connectionFuture.exception);
            }
        });
    } catch (e) {
        handleException(e);
    }
};

Run the modified app, and notice the log message indicating that the topic has been created.

Topic created...
JMS session created

To see and run the updated code in JSFiddle, point your browser to the Task 3 state: http://jsfiddle.net/R5qc3/3.

Task 4: Creating the producer
In this task we create a producer. The producer or publisher in the JMS world is a client that creates and sends messages. Let’s call our producer topicProducer and invoke the createProducer() function on the session object. When done, let’s create a log message indicating the successful creation of the producer.

topicProducer = session.createProducer(myTopic);
consoleLog("Topic producer created...");

Here’s the entire JavaScript file. Look for Task 4 in the comments to find the newly added createProducer() function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Variables you can change
//
var MY_WEBSOCKET_URL = "ws://tutorial.kaazing.com/jms";
var TOPIC_NAME = "/topic/myTopic";
var IN_DEBUG_MODE = true;
var DEBUG_TO_SCREEN = true;
 
// WebSocket and JMS variables
//
var connection;
var session;
var wsUrl;
 
// JSFiddle-specific variables
//
var runningOnJSFiddle = (window.location.hostname === "fiddle.jshell.net");
var WEBSOCKET_URL = (runningOnJSFiddle ? MY_WEBSOCKET_URL : "ws://" + window.location.hostname + ":" + window.location.port + "/jms");
 
// Variable for log messages
//
var screenMsg = "";
 
// Used for development and debugging. All logging can be turned
// off by modifying this function.
//
var consoleLog = function(text) {
    if (IN_DEBUG_MODE) {
        if (runningOnJSFiddle || DEBUG_TO_SCREEN) {
            // Logging to the screen
            screenMsg = screenMsg + text + "<br>";
            $("#logMsgs").html(screenMsg);
        } else {
            // Logging to the browser console
            console.log(text);
        }
    }
<